library(tidyverse)
library(readxl)
library(respR)
library(dplyr)
library(nlme)
library(lme4)
library(performance)
library(MuMIn)
library(corrplot)
library(DHARMa)
library(glmmTMB)
library(cowplot)
library(ggplot2)

Theme = theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank(),axis.title=element_text(size=20),
              axis.text=element_text(size=18),strip.text = element_text(size = 16),legend.text = element_text(size=14),legend.title = element_text(size=16))

#Questions
#Does metabolism correlate with successful survival in salmon
#Does it correlate with earlier migration in salmon
#Is anything happebing with trout

# Load Data ---------------------------------------------------------------
Fin = read_csv("Processed Data/Final_Data.csv")
table(Fin$System2)
#Same data removal as before
sum(!is.na(Fin$tag))

Fin=subset(Fin, is.na(Check))
Fin=subset(Fin, Run_un !="Frome2_3_1")

Fin_EX=Fin
Fin <- Fin%>%
  drop_na(MR_MT, G_day_S, Temp, Age, Condition,System)
#Fin <- Fin %>%
#  filter(!(Age < 1 & System2 != "Frome2"))
171+88+28+6
#Remove untagged rivers
Fin=subset(Fin, !(System2 %in% c("Cantabria","Sunnudalsa","Frome")))

Num <- subset(Fin, !is.na(tag))

table(Num$System2)

#0 Migration timing
Fin = Fin %>%
  group_by(System2) %>%
  mutate(Timing2 = (Timing - min(Timing, na.rm = TRUE))/ 86400) %>%
  ungroup()
Fin$Timing2=as.numeric(round(Fin$Timing2))

#Recode migration
Fin=mutate(Fin, Migrant=ifelse(is.na(Migrant),"No",Migrant))
Fin=mutate(Fin, Mig2=ifelse(Migrant=="No",0,1))

#Numbers
table(Fin$Migrant,Fin$SP)
86/(712+86)

#Remove returner
Fin=subset(Fin, Migrant != "Returner")

#Add Temp and NDVI
meta = data.frame(
  System2 = c("Cantabria", "Frome2", "Tweed", "Deveron", "Sunnudalsa", "Vesta"),
  Mean_temp = c(10.5, 10.3, 8.1, 7.7, 1.3, 1.3),
  NDVI = c(0.638, 0.724, 0.664, 0.603, 0.240, 0.238)
)
Fin=merge(Fin, meta, by=c("System2"))
#Center Condition
Fin$Condition_mean_sys <- ave(
  Fin$Condition,
  Fin$System2,
  FUN = mean
)

Fin$Condition_within_sys <- 
  Fin$Condition - Fin$Condition_mean_sys

#Subset migrants
Mig=subset(Fin, Migrant=="Yes")
Mig=subset(Mig, SP=="Salmon")

ggplot(Mig, aes(x=Timing, fill=System2))+geom_histogram()


# VDA ---------------------------------------------------------------------

#Migrant or dont migrate
ggplot(Fin, aes(x=log(MR_MT),fill=Migrant))+geom_histogram()+facet_wrap(~System2)
ggplot(Fin, aes(y=log(MR_MT),x=Migrant,fill=System2))+geom_boxplot()+facet_wrap(~System2)
ggplot(Fin, aes(y=kT,x=Migrant,fill=System2))+geom_boxplot()+facet_wrap(~System2)

ggplot(Mig, aes(x=log(MR_M),fill=System2))+geom_histogram()+facet_wrap(~SP)#No trout

#Timing
ggplot(Mig, aes(x=Timing,fill=System2))+geom_histogram()
ggplot(Mig, aes(x=Timing2,y=log(MR_MT),color=System2))+geom_point()+geom_smooth()
ggplot(Mig, aes(x=Timing2,y=log(MR_MT)))+geom_point()+geom_smooth(method="lm")
ggplot(Mig, aes(x=Timing2,y=Temp))+geom_point()+geom_smooth(method="lm")
ggplot(Mig, aes(x=Timing2,y=Temp))+geom_point()+geom_smooth(method="lm")
ggplot(Mig, aes(x=Timing2,y=Mass))+geom_point()+geom_smooth(method="lm")
ggplot(Mig, aes(x=Timing2,y=Condition))+geom_point()+geom_smooth(method="lm")





# Survival with water temp --------------------------------------------------

#Full two way interaction model
global_model <- glmer(
  Mig2 ~ 
    (log(MR_MT) + Annual_Mean_temp  + log(Mass) + Age)^2 +
    (1 | System2),
  data = Fin,
  family = binomial,
  na.action = "na.fail"
)#growth in the first year excluded, best from this model has Age*Temp+Age*Mass+Temp*Mass+Condition+Mass+Temp+Age but VIF a unworkable disatser

global_model <- glmer(
  Mig2 ~ 
    log(MR_MT) +
    Annual_Mean_temp +
    log(Mass) +
    log(Mass)*Annual_Mean_temp+
    (1 | System2),
  data = Fin,
  family = binomial,
  na.action = "na.fail"
)

model_set <- dredge(global_model, rank = "AICc")
global_model <- get.models(model_set, 1)[[1]]

check_model(global_model)
summary(global_model)


#Instead do stepwise term removal to get this with an interaction that must be removed due to high VIF
m_mig <- glmer(
  Mig2 ~ 
    log(MR_MT) +
    Annual_Mean_temp +
    log(Mass) +
    Annual_Mean_temp:log(Mass) +
    (1 | System2),data = Fin,family = binomial,na.action = "na.fail")

summary(m_mig)
check_model(m_mig)#Looks acceptable, if you rescale variables then VIF fine and same result
r2(m_mig)
library(car)
vif(m_mig)

#-----------------------------
# 1. Summary values
#-----------------------------
means <- Fin %>%
  summarise(
    MR_MT = mean(MR_MT, na.rm = TRUE),
    Annual_Mean_temp = mean(Annual_Mean_temp, na.rm = TRUE),
    Mass = mean(Mass, na.rm = TRUE)
  )

n <- 100

#-----------------------------
# 2. Main effect predictions
#-----------------------------

# MR_MT
pred_mr <- data.frame(
  MR_MT = seq(min(Fin$MR_MT, na.rm = TRUE),
              max(Fin$MR_MT, na.rm = TRUE),
              length.out = n),
  Annual_Mean_temp = means$Annual_Mean_temp,
  Mass = means$Mass
) %>%
  mutate(
    variable = "MR_MT",
    x = log(MR_MT)
  )

# Temperature
pred_temp <- data.frame(
  MR_MT = means$MR_MT,
  Annual_Mean_temp = seq(min(Fin$Annual_Mean_temp, na.rm = TRUE),
                         max(Fin$Annual_Mean_temp, na.rm = TRUE),
                         length.out = n),
  Mass = means$Mass
) %>%
  mutate(
    variable = "Annual_Mean_temp",
    x = Annual_Mean_temp
  )

# Mass
pred_mass <- data.frame(
  MR_MT = means$MR_MT,
  Annual_Mean_temp = means$Annual_Mean_temp,
  Mass = seq(min(Fin$Mass, na.rm = TRUE),
             max(Fin$Mass, na.rm = TRUE),
             length.out = n)
) %>%
  mutate(
    variable = "Mass",
    x = log(Mass)
  )

#-----------------------------
# 3. Interaction predictions
#-----------------------------

temp_vals <- c(
  min(Fin$Annual_Mean_temp, na.rm = TRUE),
  mean(Fin$Annual_Mean_temp, na.rm = TRUE),
  max(Fin$Annual_Mean_temp, na.rm = TRUE)
)

pred_int <- expand.grid(
  MR_MT = means$MR_MT,
  Annual_Mean_temp = temp_vals,
  Mass = seq(min(Fin$Mass, na.rm = TRUE),
             max(Fin$Mass, na.rm = TRUE),
             length.out = n)
) %>%
  mutate(
    variable = "Temp × Mass",
    x = log(Mass),
    Temp_group = factor(
      Annual_Mean_temp,
      levels = temp_vals,
      labels = c(
        paste0("Min temp (", round(temp_vals[1], 1), "°C)"),
        paste0("Mean temp (", round(temp_vals[2], 1), "°C)"),
        paste0("Max temp (", round(temp_vals[3], 1), "°C)")
      )
    )
  )
#-----------------------------
# 4. Combine predictions
#-----------------------------
pred_all <- bind_rows(
  pred_mr,
  pred_temp,
  pred_mass,
  pred_int
)

#-----------------------------
# 5. Predictions + CI
#-----------------------------
pred_link <- predict(
  m_mig,
  newdata = pred_all,
  type = "link",
  se.fit = TRUE,
  re.form = NA
)

pred_all$fit_link <- pred_link$fit
pred_all$se_link  <- pred_link$se.fit

pred_all <- pred_all %>%
  mutate(
    pred  = plogis(fit_link),
    lower = plogis(fit_link - 1.96 * se_link),
    upper = plogis(fit_link + 1.96 * se_link)
  )

#-----------------------------
# 6. Raw data
#-----------------------------
raw_all <- bind_rows(
  
  Fin %>%
    mutate(
      variable = "MR_MT",
      x = log(MR_MT)
    ),
  
  Fin %>%
    mutate(
      variable = "Annual_Mean_temp",
      x = Annual_Mean_temp
    ),
  
  Fin %>%
    mutate(
      variable = "Mass",
      x = log(Mass)
    ),
  
  Fin %>%
    mutate(
      variable = "Temp × Mass",
      x = log(Mass),
      Temp_group = cut(
        Annual_Mean_temp,
        breaks = quantile(
          Annual_Mean_temp,
          probs = c(0, 0.33, 0.66, 1),
          na.rm = TRUE
        ),
        include.lowest = TRUE,
        labels = c("Low temp", "Mean temp", "High temp")
      )
    )
)

#-----------------------------
# 7. Plot
#-----------------------------
ggplot() +
  
  geom_point(
    data = raw_all,
    aes(x = x, y = Mig2),
    alpha = 0.2
  ) +
  
  geom_ribbon(
    data = pred_all %>% 
      filter(variable != "Temp × Mass"),
    aes(
      x = x,
      ymin = lower,
      ymax = upper
    ),
    alpha = 0.2,
    fill = "black"
  ) +
  
  geom_line(
    data = pred_all %>% 
      filter(variable != "Temp × Mass"),
    aes(x = x, y = pred),
    linewidth = 1.2,
    colour = "black"
  ) +
  
  geom_ribbon(
    data = pred_all %>% 
      filter(variable == "Temp × Mass"),
    aes(
      x = x,
      ymin = lower,
      ymax = upper,
      fill = Temp_group
    ),
    alpha = 0.15
  ) +
  
  geom_line(
    data = pred_all %>% 
      filter(variable == "Temp × Mass"),
    aes(
      x = x,
      y = pred,
      colour = Temp_group
    ),
    linewidth = 1.2
  ) +
  
  facet_wrap(
    ~variable,
    scales = "free_x",
    ncol = 2,
    labeller = as_labeller(c(
      MR_MT = "ln(Mass- and temperature-\ncorrected metabolism)",
      Annual_Mean_temp = "Temperature (°C)",
      Mass = "ln(Mass(g))",
      `Temp × Mass` = "Temperature (°C) × ln(Mass(g))"
    ))
  ) +
  
  labs(
    x = "Predictor value",
    y = "Detected survival probability",
    colour = "Temperature",
    fill = "Temperature"
  ) +
  
  theme_bw() +
  Theme


#NOW MERGE MIGRATION TIMING



#Predict and plot
ggsave("Plots/Survival vs key factors.tiff", width = 9, height = 8, units = "in", dpi = 300)




# Movement with water temp --------------------------------------------------
#I think the best way toi approach this is to normalise between all rivers with Age and Mass, metabolism already is and temperature is fixed,
#bear in mind the migration timing has had the same done to it.


library(survival)
library(coxme)

m_time <- coxme(Surv(Timing2) ~ log(MR_MT)*Annual_Mean_temp+log(MR_MT)*log(Mass)+log(MR_MT)*Condition+
                  Annual_Mean_temp*log(Mass)+Annual_Mean_temp*Condition+log(Mass)*Condition+Age*Condition+Age*Annual_Mean_temp+Age*log(MR_MT)+Age*log(Mass) + (1|System),
                data = Mig,na.action="na.fail")#Remove sig terms

#Try better nesting age and mass
Mig$Mass_mean_age_sys <- ave(log(Mig$Mass), Mig$System, Mig$Age, FUN = mean)
Mig$Mass_within_age_sys <- log(Mig$Mass) - Mig$Mass_mean_age_sys

Mig$Age_mean_sys <- ave(Mig$Age, Mig$System, FUN = mean)
Mig$Age_within_sys <- Mig$Age - Mig$Age_mean_sys

m_time <- coxme(
  Surv(Timing2) ~ 
    log(MR_MT)*Annual_Mean_temp +
    log(MR_MT)*Mass_within_age_sys +
    log(MR_MT)*Condition +
    Annual_Mean_temp*Condition +
    Mass_within_age_sys*Condition +
    Age_within_sys +                          # control for ontogeny
    (1 | System),
  data = Mig,
  na.action = "na.fail"
)



model_set <- dredge(m_time, rank = "AIC")
m_time <- get.models(model_set, 1)[[1]]#However VIF issues so simplify till best model
check_model(m_time, residual_type = "normal")#variance inflation too high so interactive term removed



m_time <- coxme(Surv(Timing2) ~ Condition+log(MR_MT)+Mass_within_age_sys+Annual_Mean_temp + (1|System),
                data = Mig,na.action="na.fail")#TEST - Based on Rasmuses feeback this seems the best model, can also remove condition for simplicity


summary(m_time)

m_time <- coxme(Surv(Timing2) ~ Age+Condition+log(MR_MT)+log(Mass) + (1|System),
                data = Mig,na.action="na.fail")

m_time <- coxph(Surv(Timing2) ~ Age+Condition+log(MR_MT)+log(Mass),
                data = Mig,na.action="na.fail")#For plot



m_time <- coxme(Surv(Timing2) ~ Age+Condition+log(MR_MT)+log(Mass) + (1|System),
                data = Mig,na.action="na.fail")

#model and plot
beta <- fixef(m_time)
se   <- sqrt(diag(vcov(m_time)))

coef_df <- data.frame(
  term = names(beta),
  HR   = exp(beta),
  LCL  = exp(beta - 1.96 * se),
  UCL  = exp(beta + 1.96 * se)
)

tm1 = ggplot(coef_df, aes(HR, term)) +
  geom_point(size=3) +
  geom_errorbarh(aes(xmin=LCL, xmax=UCL), height=0.15) +
  geom_vline(xintercept=1, linetype="dashed") +
  labs(x="Hazard Ratio", y=NULL) +
  theme_bw() + Theme +
  scale_y_discrete(labels = c(
    "log(MR_MT)" = "ln(mass and temperature\ncorrected metabolism)",
    "Condition"  = "Condition factor",
    "log(Mass)"  = "ln (Mass (g))",
    "Age"        = "Age"
  ))

#-----------------------------
# PLOT 2: Survival predictions
#-----------------------------

# helpers
lh  <- function(x) quantile(x, c(.1,.9), na.rm=TRUE)
med <- function(x) median(x, na.rm=TRUE)

# values
MR    <- lh(Mig$MR_MT); Mass <- lh(Mig$Mass)
Cond  <- lh(Mig$Condition); Age <- lh(Mig$Age)

MRm   <- med(Mig$MR_MT); Massm <- med(Mig$Mass)
Condm <- med(Mig$Condition); Agem <- med(Mig$Age)

# prediction data
newdat <- bind_rows(
  data.frame(MR_MT=MR,  Mass=Massm, Condition=Condm, Age=Agem,
             level=c("Low","High"), var="(e) ln (mass and temperature\ncorrected metabolism)"),
  data.frame(MR_MT=MRm, Mass=Mass,  Condition=Condm, Age=Agem,
             level=c("Low","High"), var="(d) ln (Mass (g))"),
  data.frame(MR_MT=MRm, Mass=Massm, Condition=Cond,  Age=Agem,
             level=c("Low","High"), var="(c) Condition factor"),
  data.frame(MR_MT=MRm, Mass=Massm, Condition=Condm, Age=Age,
             level=c("Low","High"), var="(b) Age")
)

# NOTE: survfit does not support coxme → use fixed effects only
sf <- survfit(
  coxph(Surv(Timing2) ~ Age + Condition + log(MR_MT) + log(Mass),
        data = Mig, na.action="na.fail"),
  newdata = newdat
)

# tidy predictions
tidy_sf <- lapply(seq_len(ncol(sf$surv)), function(i) {
  data.frame(
    time  = sf$time,
    surv  = sf$surv[,i],
    lower = sf$lower[,i],
    upper = sf$upper[,i],
    var   = newdat$var[i],
    level = newdat$level[i]
  )
}) |> bind_rows()

# observed KM
km <- with(survfit(Surv(Timing2) ~ 1, Mig),
           data.frame(time, surv))

# plot
tm2 = ggplot(tidy_sf, aes(time, surv, colour=level, fill=level)) +
  geom_line(linewidth=1) +
  geom_ribbon(aes(ymin=lower, ymax=upper), alpha=.15, colour=NA) +
  geom_step(data=km, aes(time, surv), inherit.aes=FALSE, colour="black") +
  facet_wrap(~var, scales="free_y") +
  labs(x="Days", y="Migration probability", colour="Level", fill="Level") +
  theme_bw() + Theme

#-----------------------------
# COMBINE + SAVE
#-----------------------------
timing = plot_grid(tm1, tm2, ncol=1, rel_heights=c(1,2), labels=c("(a)"))

ggsave("Plots/Timing.tiff", plot = timing, width = 8.5, height = 11, units = "in", dpi = 150)









##############JUNK

# Quick Modelling (NEEDS WORK) ---------------------------------------------------------

#Mig and netabolism

#Can maybe group by system but too poor sampling for any more
ggplot(Fin, aes(y=log(MR_MT),x=Migrant))+geom_boxplot()
ggplot(Fin, aes(y=(Temp),x=Migrant))+geom_boxplot()
global_model <- glmer(Mig2 ~ log(MR_M)*System2*Temp+Condition+G1+log(Mass) + (1|System2),
            data=Fin,
            family=binomial,na.action="na.fail")
model_set <- dredge(global_model, rank = "AICc")
m_mig <- get.models(model_set, 1)[[1]]
table(Fin$Mig2)

Fin$logMR_M=log(Fin$MR_M)#may fix graph issue

m_mig <- glmer(
  Mig2 ~ Condition + logMR_M + Temp + (1|System2),
  family = binomial(link = "probit"),
  data = Fin#Slightly better
)
library(performance)
r2(m_mig)

#Beta binmial seems to fix residuals (same resdult probably dont need but good to know)
m_mig <- glmmTMB(Mig2 ~ Condition + log(MR_M) + Temp + (1 | System2),
                 family = betabinomial,
                 data = Fin)


summary(m_mig)
ranef(m_mig)#Base binomial looks mostly fine but Beta fixes all issues, can use either)



check_model(m_mig)#Fish with a lower metabolism more likley to survive to migrate
plot(simulateResiduals(m_mig))
performance::check_overdispersion(m_mig)
testDispersion(m_mig)


# Plots -------------------------------------------------------------------

library(effects)
plot(allEffects(m_mig))

library(ggeffects)
p_cond <- ggpredict(m_mig, terms = "Condition")#Wont include as non significant
p_mr   <- ggpredict(m_mig,terms="logMR_M [all]")
p_temp <- ggpredict(m_mig, terms = "Temp")

#Conditon
p1 <- ggplot(p_cond, aes(x = (x), y = predicted)) +
  geom_line(size = 1.1) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = 0.2) +
  labs(x = "Condition",y = "Predicted survival probability")+theme_bw()+Theme
#Metabolism
p2 <- ggplot(p_mr, aes(x = (x), y = predicted)) +
  geom_line(size = 1.1) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = 0.2) +
  labs(x = "Log mass corrected metabolism",y = "Predicted survival probability")+theme_bw()+Theme+ylim(0,0.3)
#Temperature
p3 <- ggplot(p_temp, aes(x = (x), y = predicted)) +
  geom_line(size = 1.1) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = 0.2) +
  labs(x = "Temperature (°C)",y = "Predicted survival probability")+theme_bw()+Theme+ylim(0,0.3)+ theme(
    axis.title.y = element_blank(),
    axis.text.y  = element_blank(),
    axis.ticks.y = element_blank(),
    axis.line.y  = element_blank()
  )

#Or with data plotted
p_mr <- ggpredict(m_mig, terms = "logMR_M")

#Metabolism
p2 <- ggplot() +
  geom_jitter(data = Fin,
              aes(x = logMR_M, y = Mig2),
              width = 0, height = 0.05, alpha = 0.25, size = 1.5) +
  geom_ribbon(data = p_mr,
              aes(x = x, ymin = conf.low, ymax = conf.high),
              alpha = 0.2) +
  geom_line(data = p_mr,
            aes(x = x, y = predicted),
            size = 1.1) +
  labs(x = "Log mass corrected metabolism",y = "Predicted survival probability")+theme_bw()+Theme

#Temperature
p3 <- ggplot() +
  geom_jitter(data = Fin,
              aes(x = Temp, y = Mig2),
              width = 0, height = 0.05, alpha = 0.25, size = 1.5) +
  
  geom_ribbon(data = p_temp,
              aes(x = x, ymin = conf.low, ymax = conf.high),
              alpha = 0.2) +
  geom_line(data = p_temp,
            aes(x = x, y = predicted),
            size = 1.1) +
  labs(x = "Temperature (°C)", y = "Survival probability") +theme_bw()+Theme+theme(
    axis.title.y = element_blank(),
    axis.text.y  = element_blank(),
    axis.ticks.y = element_blank(),
    axis.line.y  = element_blank())

survive = plot_grid(p2,p3,ncol=2)
ggsave("Plots/Survival vs metabolism and temp.tiff", plot = survive, width = 11, height = 6, units = "in", dpi = 300)






#Timing

m_time <- lmer(as.numeric(Timing2) ~ log(MR_M) + (1|System),
               data = Mig)
summary(m_time)
str(Mig)#no obvious linear trend

library(survival)
library(coxme)

m_time <- coxme(Surv(Timing2, Mig2) ~ log(MR_M)+kT+Condition+Mass + (1|System),
                 data = Fin,)
m_time2 <- coxme(Surv(Timing2, Mig2) ~ kT+Condition+Mass + (1|System),
                data = Fin,)

######
m_time <- coxme(Surv(Timing2) ~ log(MR_M)*kT*(Mass)*Condition + (1|System),
                data = Mig,na.action="na.fail")
AIC(m_time)
#Model selection
model_set <- dredge(m_time, rank = "AICc")
m_time <- get.models(model_set, 1)[[1]]


citation("survival")

AIC(m_time,m_time2)

summary(m_time)
check_model(m_time)#variance inflation too high so interactive term removed
m_time <- coxme(Surv(Timing2, Mig2) ~ kT+Condition+log(Mass)+log(MR_M) + (1|System),
                 data = Fin,)
summary(m_time)


#Is this within or between systems (MAY NEED TO ADD to other models)
Fin$kT_mean_sys  <- ave(Fin$kT, Fin$System2, FUN = mean)
Fin$kT_within    <- Fin$kT - Fin$kT_mean_sys

m_time2 <- coxme(
  Surv(Timing2, Mig2) ~ kT_within + kT_mean_sys + log(MR_M) +
    Condition + Mass + (1 | System),
  data = Fin
)



###Look at plots from Plots Ph to get hazard curves
#look at how bets to code it up and check input data, just want on migratory fish and the event time (normalised)

summary(m_time2)
#Temp and Mass lead to earlier migration, condition leads to later or no migration, metabolism leads to ealrier migration but non signifiant.


# Timing Plots ------------------------------------------------------------

#Can only plot fixed effects:
Mig$LogMass=log(Mig$Mass)
m_fixed <- coxph(Surv(Timing2) ~ log(MR_M)+Condition+log(Mass) + kT,
                 data = Mig)
summary(m_fixed)

newdat <- data.frame(
  MR_M      = quantile(Mig$MR_M, probs = c(.1, .5, .9), na.rm = TRUE),
  kT        = median(Mig$kT),
  Condition = median(Mig$Condition),
  Mass      = median(log(Mig$Mass))
)
sf <- survfit(m_fixed, newdata=newdat)

to_df <- function(sf, newdat) {
  out <- lapply(seq_along(sf$strata), function(i) {
    data.frame(
      time = sf$time,
      surv = sf$surv[,i],
      upper = sf$upper[,i],
      lower = sf$lower[,i],
      group = paste0("MR_M=", round(newdat$MR_M[i],3))
    )
  })
  do.call(rbind, out)
}

df_sf <- to_df(sf, newdat)

summ <- summary(m_fixed)

coef_df <- data.frame(
  term = rownames(summ$coefficients),
  HR   = exp(summ$coefficients[,"coef"]),
  LCL  = exp(summ$coefficients[,"coef"] - 1.96*summ$coefficients[,"se(coef)"]),
  UCL  = exp(summ$coefficients[,"coef"] + 1.96*summ$coefficients[,"se(coef)"])
)

tm1 = ggplot(coef_df, aes(HR, term)) +
  geom_point(size=3) +
  geom_errorbarh(aes(xmin=LCL, xmax=UCL), height=0.15) +
  geom_vline(xintercept=1, linetype="dashed") +
  labs(x="Hazard Ratio", y=NULL)+theme_bw()+Theme+
  scale_y_discrete(labels = c(
    "log(MR_M)"            = "log Metabolism",
    "Condition"            = "Condition",
    "log(Mass)"                 = "log Mass",
    "kT"                   = "Temperature",
    "log(MR_M):Condition"  = "Metabolic rate × Condition"
  ))


ggforest(m_fixed, data = Mig)


termplot(m_fixed, se = TRUE)

#Random effects (dont want)
re <- ranef(m_time)$System
barplot(re, las=2, ylab="Random effect (system frailty)")


#Migration probability curves foioir all model factors

# 1. Define high/low values
# --------------------------
low_high <- function(x) quantile(x, c(0.1, 0.9), na.rm = TRUE)

MR_vals   <- low_high(Mig$MR_M)
kT_vals   <- low_high(Mig$kT)
Mass_vals <- low_high(Mig$Mass)
Cond_vals <- low_high(Mig$Condition)   # <-- added

Cond_med <- median(Mig$Condition, na.rm = TRUE)
G1_med   <- median(Mig$G1, na.rm = TRUE)

# ----------------------------------
# 2. Build prediction scenarios (INCLUDING CONDITION)
# ----------------------------------
newdat <- rbind(
  # Metabolism
  data.frame(MR_M = MR_vals[1], kT = median(Mig$kT), Mass = median(Mig$Mass),
             Condition = Cond_med, G1 = G1_med,
             level = "Low", variable = "Metabolism"),
  
  data.frame(MR_M = MR_vals[2], kT = median(Mig$kT), Mass = median(Mig$Mass),
             Condition = Cond_med, G1 = G1_med,
             level = "High", variable = "Metabolism"),
  
  # Temperature (kT)
  data.frame(MR_M = median(Mig$MR_M), kT = kT_vals[1], Mass = median(Mig$Mass),
             Condition = Cond_med, G1 = G1_med,
             level = "Low", variable = "Temperature"),
  
  data.frame(MR_M = median(Mig$MR_M), kT = kT_vals[2], Mass = median(Mig$Mass),
             Condition = Cond_med, G1 = G1_med,
             level = "High", variable = "Temperature"),
  
  # Mass
  data.frame(MR_M = median(Mig$MR_M), kT = median(Mig$kT), Mass = Mass_vals[1],
             Condition = Cond_med, G1 = G1_med,
             level = "Low", variable = "Mass"),
  
  data.frame(MR_M = median(Mig$MR_M), kT = median(Mig$kT), Mass = Mass_vals[2],
             Condition = Cond_med, G1 = G1_med,
             level = "High", variable = "Mass"),
  
  # --------------------------
  # Condition (NEW)
  # --------------------------
  data.frame(MR_M = median(Mig$MR_M), kT = median(Mig$kT), Mass = median(Mig$Mass),
             Condition = Cond_vals[1], G1 = G1_med,
             level = "Low", variable = "Condition"),
  
  data.frame(MR_M = median(Mig$MR_M), kT = median(Mig$kT), Mass = median(Mig$Mass),
             Condition = Cond_vals[2], G1 = G1_med,
             level = "High", variable = "Condition")
)

# --------------------------
# 3. Fit coxph for predictions
# --------------------------
m_fixed <- coxph(
  Surv(Timing2) ~ log(MR_M) + kT + Condition + log(Mass) + G1,
  data = Mig
)

sf <- survfit(m_fixed, newdata = newdat)

# ---------------------------------------------------------
# 4. Convert survfit object to tidy data frame for ggplot
# ---------------------------------------------------------
n_curves <- if (!is.null(ncol(sf$surv))) ncol(sf$surv) else 1

tidy_sf <- lapply(seq_len(n_curves), function(i) {
  data.frame(
    time  = sf$time,
    surv  = if (n_curves == 1) sf$surv else sf$surv[, i],
    lower = if (n_curves == 1) sf$lower else sf$lower[, i],
    upper = if (n_curves == 1) sf$upper else sf$upper[, i],
    variable = newdat$variable[i],
    level    = newdat$level[i]
  )
}) |> dplyr::bind_rows()

# --------------------------
# 5. Plot faceted survival curves
# --------------------------
ggplot(tidy_sf, aes(time, surv, colour = level, fill = level)) +
  geom_line(size = 1) +
  geom_ribbon(aes(ymin = lower, ymax = upper), alpha = 0.15, colour = NA) +
  facet_wrap(~ variable, scales = "free_y") +
  labs(
    x = "Days",
    y = "Migration probability",
    colour = "Level",
    fill = "Level"
  ) +theme_bw()+Theme

#add real data
sf_obs <- survfit(Surv(Timing2) ~ 1, data = Mig)
km_obs <- data.frame(
  time  = sf_obs$time,
  surv  = sf_obs$surv
)
facet_labels <- c(
  Condition = "(b) Condition",
  Mass      = "(c) log Mass",
  Temperature        = "(e) Temperature",
  Metabolism   = "(d) log Metabolism"
)
tm2 <- ggplot(tidy_sf, aes(time, surv, colour = level, fill = level)) +
  geom_line(size = 1) +
  geom_ribbon(aes(ymin = lower, ymax = upper), alpha = 0.15, colour = NA) +
  geom_step(data = km_obs, aes(x = time, y = surv),
            inherit.aes = FALSE, colour = "black", linewidth = 1) +
  geom_point(data = km_obs, aes(x = time, y = surv),
             inherit.aes = FALSE, colour = "black", size = 1.2) +
  facet_wrap(
    ~ variable,
    scales = "free_y",
    labeller = as_labeller(facet_labels)
  ) +
  labs(
    x = "Days",
    y = "Migration probability",
    colour = "Level",
    fill = "Level"
  ) +
  theme_bw() +
  Theme

##Plots
timing=plot_grid(tm1,tm2,ncol=1, rel_heights = c(1, 2),
                 labels = c("(a)"))
ggsave("Plots/Timing.tiff", plot = timing, width = 7, height = 10, units = "in", dpi = 300)



# Extra Frome -------------------------------------------------------------

Fin_EX <- Fin_EX%>%
  drop_na(MR_MT, Temp, Condition,System)
#Fin <- Fin %>%
#  filter(!(Age < 1 & System2 != "Frome2"))

#Remove untagged rivers
Fin_EX=subset(Fin_EX, !(System2 %in% c("Cantabria","Sunnudalsa")))



table(Fin_EX$Migrant, Fin_EX$System2)

#0 Migration timing
Fin_EX = Fin_EX %>%
  group_by(System2) %>%
  mutate(Timing2 = (Timing - min(Timing, na.rm = TRUE))/ 86400) %>%
  ungroup()
Fin_EX$Timing2=as.numeric(round(Fin_EX$Timing2))

#Recode migration
Fin_EX=mutate(Fin_EX, Migrant=ifelse(is.na(Migrant),"No",Migrant))
Fin_EX=mutate(Fin_EX, Mig2=ifelse(Migrant=="No",0,1))

#Remove returner
Fin_EX=subset(Fin_EX, Migrant != "Returner")

#Subset migrants
Mig=subset(Fin_EX, Migrant=="Yes")

#Select key terms
Fin_EX=select(Fin_EX, MR_M,System2, Condition, Temp, Mass, Timing2, Mig2)


#Now bring in Frome 2021
Fr21<- read_csv("C:/Users/peter/OneDrive/Life/Marine Biology/PhD Metabolic Drivers of Growth and Survival in Salmonids/Chapters/Data/Frome/2021 and 2019/dorset_fish_metabolism.csv")
Fr21$MR_M=Fr21$MR/Fr21$Weigth_g^0.84

#Merge with migration data
Frome <- read.csv("Raw Data/Frome PeterBetts-MetabolicFish-Detections-2025-10.csv")
Frome = mutate(Frome, Migrant=ifelse(movement_status=="Smolt","Yes","No"))
FromeF=subset(Frome, Migrant=="Yes")
FromeF=FromeF%>%
  group_by(tag,Migrant)%>%
  summarise(Timing=max(date))
#Merge and Bind
FromeF$Timing=as_datetime(FromeF$Timing)
FromeF=rename(FromeF, Tag=tag)
Fr21 = merge(Fr21, FromeF, by=c("Tag"),all.x=TRUE)
Fr21=rename(Fr21,Temp=MeanT_Chamber,Mass=Weigth_g,System2=System)
Fr21$Condition=(100*Fr21$Mass/(Fr21$Furcal_Length_mm/10)^3)

#0 Migration timing
Fr21 = Fr21 %>%
  group_by(System2) %>%
  mutate(Timing2 = (Timing - min(Timing, na.rm = TRUE))/ 86400) %>%
  ungroup()

#Recode migration
Fr21=mutate(Fr21, Migrant=ifelse(is.na(Migrant),"No",Migrant))
Fr21=mutate(Fr21, Mig2=ifelse(Migrant=="No",0,1))

Fr21=select(Fr21, MR_M, System2,Condition, Temp, Mass,Timing2, Mig2)
#Fr21=subset(Fr21, Timing2<300)

Fin_EX=rbind(Fr21, Fin_EX)

#Fin_EX=subset(Fin_EX, System2!="Frome19") #Can remove Frome19
table(Fin_EX$System2,Fin_EX$Mig2)

#Fin_EX2=mutate(Fin_EX, Timing2 = ifelse(is.na(Timing2)==FALSE&Timing2>365, Timing2-365,Timing2)) #Can remove fish that migrated a year late


#Model (no growth or age)
global_model <- glmer(Mig2 ~ log(MR_M)*System2*Temp+Condition+Mass + (1|System2),
                      data=Fin_EX,
                      family=binomial,na.action="na.fail")
model_set <- dredge(global_model, rank = "AICc")
m_mig <- get.models(model_set, 1)[[1]]
m_mig<- glmer(Mig2 ~ log(MR_M)*Temp+Condition+Mass + (1|System2),
         data=Fin_EX,
         family=binomial,na.action="na.fail")
summary(m_mig)
check_model(m_mig)#Fish with a lower metabolism more likley to survive to migrate
plot(simulateResiduals(m_mig))
performance::check_overdispersion(m_mig)

#With Fome 21 see the same [attern, with all frome data that pattern goes, excluding just 19 see a reverse effect to before]
ggplot(Fin_EX, aes(y=log(MR_M),x=as.character(Mig2)))+geom_boxplot()+facet_wrap(~System2)
ggplot(Fin_EX, aes(y=(Temp),x=as.character(Mig2)))+geom_boxplot()


m_time <- coxme(Surv(Timing2, Mig2) ~ log(MR_M)+Temp+Condition+Mass + (1|System2),
                data = Fin_EX,)

summary(m_time)

#remove fish that went the next year or remove 365 from them
#try again with all data